﻿using UnityEngine;
using System.Collections;
using System.Timers;

namespace Framework.AssetsManager
{
    public class NetLoader
    {
        private string m_url = null;

        private WWW m_www = null;

        private bool m_isDone = false;
        private bool m_error = false;

        static private NetLoaderRunner m_runner = NetLoaderRunner.Instance;

        public delegate void onFinish(WWW _www, AssetBundle _ab);
        public delegate void onProgress(float progress);
        public delegate void onError(string error);

        public onFinish OnLoaderFinish = null;
        public onProgress OnLoaderProcess = null;
        public onError OnLoaderError = null;

        public NetLoader(string url)
        {
            m_url = url;
        }

        public static void SetNetLoaderRunner(NetLoaderRunner runner) { m_runner = runner; }
        public static NetLoaderRunner GetNetLoaderRunner() { return m_runner; }

        public void Load(bool _useCache, int _version = 0)
        {
            if (m_url == null)
            {
                Debug.LogError("NetLoader error: url is null");
                return;
            }

            if (m_runner == null)
            {
                Debug.LogError("NetLoader error: runner is null");
                return;
            }

            if (m_www != null)
            {
                Debug.LogError("NetLoader error: www is existing");
                return;
            }
            m_www = new WWW(m_url);
            m_runner.Add(this);
        }

        public void UnLoad(bool _unloadObjects)
        {
            if (m_www != null && m_www.isDone)
            {
                if (m_www.assetBundle)
                {
                    m_www.assetBundle.Unload(_unloadObjects);
                }
            }
        }

        public WWW www
        {
            get { return m_www; }
        }
        public bool isDone
        {
            get { return m_isDone; }
        }
        public bool error
        {
            get { return m_error; }
        }
        public float progress
        {
            get
            {
                if (www != null)
                    return www.progress;
                else
                    return 0;
            }
        }

        public void Update()
        {
            if (OnLoaderProcess != null)
                OnLoaderProcess(m_www.progress);

            if (m_www.error != null)
            {
                if (OnLoaderError != null)
                    OnLoaderError(m_www.error);
                m_isDone = true;
                m_error = true;
            }
            else if (m_www.isDone)
            {
                if (OnLoaderFinish != null)
                    OnLoaderFinish(m_www, m_www.assetBundle);
                m_isDone = true;
                m_error = false;
            }
        }
    }
}